﻿@using Entidades.Sistema.Venta
@{
    
    Html.EnableClientValidation();
    Html.EnableUnobtrusiveJavaScript();

    var grid = Html.DevExpress().GridView(
        settings =>
        {
            settings.Name = "gvEditing";
            settings.KeyFieldName = "IdPedido";
            settings.CallbackRouteValues = new { Controller = "Pedidos", Action = "EditPedidosPartial", idcliente = ViewBag.IdCliente };
            settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Pedidos", Action = "EditPedidosAddNewPartial", idcliente = ViewBag.IdCliente };
            settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Pedidos", Action = "EditPedidosUpdatePartial", idcliente = ViewBag.IdCliente };
            settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Pedidos", Action = "EditPedidosDeletePartial", idcliente = ViewBag.IdCliente };

            settings.Columns.Add(columnImprimir =>
            {
                columnImprimir.SetDataItemTemplateContent(c =>
                {                    
                    ViewContext.Writer.Write(
                    Html.ActionLink("Imprimir", "ImprimirPedido", new { IdPedido = DataBinder.Eval(c.DataItem, "IdPedido") },
                            new { onclick = "return confirm('Realmente quiere imprimir el Pedido?')" }) );
                    });                
                columnImprimir.Settings.AllowDragDrop = DefaultBoolean.False;
                columnImprimir.Settings.AllowSort = DefaultBoolean.False;
                columnImprimir.Width = 70;
            });

            settings.Columns.Add(columnFacturar =>
            {
                columnFacturar.SetDataItemTemplateContent(c =>
                {
                    var estado = DataBinder.Eval(c.DataItem, "Estado").ToString();

                    if (estado == "Entregado" || estado == "Producido" || estado == "ParcProducido")
                    {
                        ViewContext.Writer.Write(
                        Html.ActionLink("Facturar", "EnvioFacturacion", new { IdPedido = DataBinder.Eval(c.DataItem, "IdPedido") },
                            new { onclick = "return confirm('Realmente quiere enviar a facturació el Pedido?')" }));   
                    }
                });
                columnFacturar.Settings.AllowDragDrop = DefaultBoolean.False;
                columnFacturar.Settings.AllowSort = DefaultBoolean.False;
                columnFacturar.Width = 70;
            });                
            
            settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;

            //settings.SettingsCommandButton.DeleteButton.ButtonType = GridViewCommandButtonType.Image;
            //settings.SettingsCommandButton.DeleteButton.Image.Url = Url.Content("~/Content/images/eliminarSmallBtn.png");
            
            
            settings.SettingsBehavior.ConfirmDelete = true;
            settings.SettingsPopup.EditForm.Width = 600;
            settings.SettingsPopup.EditForm.HorizontalAlign = PopupHorizontalAlign.Center;
            settings.SettingsPopup.EditForm.VerticalAlign = PopupVerticalAlign.WindowCenter;
            settings.SettingsPager.FirstPageButton.Visible = true;
            settings.SettingsPager.LastPageButton.Visible = true;
            settings.SettingsPager.PageSizeItemSettings.Visible = true;
            settings.SettingsPager.PageSizeItemSettings.Items = new string[] { "10", "20", "50" };         

            
            settings.Settings.ShowFilterRow = true;
            settings.Settings.ShowFilterRowMenu = true;
            settings.CommandColumn.Visible = true;
            settings.CommandColumn.ShowClearFilterButton = true;
            
            settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);

            settings.CommandColumn.Visible = true;
            settings.CommandColumn.ShowNewButtonInHeader = ViewBag.PermisoCreate;            
            settings.CommandColumn.ShowEditButton = ViewBag.PermisoEdit;
            settings.CommandColumn.ShowDeleteButton = ViewBag.PermisoDelete;
            

            //settings.Columns.Add("IdPedido").ReadOnly = true;

            settings.Columns.Add(column =>
            {
                column.FieldName = "Cliente.IdCliente";
                column.Caption = "Nombre Cliente";

                column.ColumnType = MVCxGridViewColumnType.ComboBox;
                var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
                comboBoxProperties.DataSource = ViewBag.Cliente;
                comboBoxProperties.TextField = "Nombre";
                comboBoxProperties.ValueField = "IdCliente";
                comboBoxProperties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.Text;
                comboBoxProperties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;
                comboBoxProperties.DropDownStyle = DropDownStyle.DropDown;

                column.SetEditItemTemplateContent(container =>
                {
                    Html.DevExpress().ComboBox(editorSettings =>
                    {
                        editorSettings.Name = "IdCliente";
                        editorSettings.Properties.TextField = "Nombre";
                        editorSettings.Properties.ValueField = "IdCliente";
                        editorSettings.Properties.Width = 120;
                        editorSettings.Properties.ValueType = typeof(int);
                        editorSettings.Properties.ValidationSettings.EnableCustomValidation = true;
                        editorSettings.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
                        editorSettings.ShowModelErrors = true;
                        editorSettings.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithTooltip;
                        editorSettings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

                    }).BindList(ViewBag.Cliente).Bind(DataBinder.Eval(container.DataItem, "Cliente.IdCliente")).Render();
                });
            });
            
            

            //ToDo: Eliminar las columnas propertiesedit
            //settings.Columns.Add(
            //    column =>
            //    {
            //        column.FieldName = "Cliente.IdCliente";
            //        column.Caption = "Nombre Cliente";

            //        column.ColumnType = MVCxGridViewColumnType.ComboBox;
            //        var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
            //        comboBoxProperties.DataSource = ViewBag.Cliente;
            //        comboBoxProperties.TextField = "Nombre";
            //        comboBoxProperties.ValueField = "IdCliente";
            //        comboBoxProperties.ValueType = typeof(int);
            //        comboBoxProperties.DropDownStyle = DropDownStyle.DropDown;
            //        comboBoxProperties.ValidationSettings.CausesValidation = false;
            //    });

            settings.Columns.Add(column =>
            {
                column.FieldName = "Fecha";
                column.Caption = "Fecha Ingreso";
                column.Width = 80;
                column.ColumnType = MVCxGridViewColumnType.DateEdit;
                column.PropertiesEdit.DisplayFormatString = "dd/MM/yyyy";
            });

            settings.Columns.Add(column =>
            {
                column.FieldName = "FechaEntrega";
                column.Caption = "FechaEntrega";
                column.Width = 80;
                column.ColumnType = MVCxGridViewColumnType.DateEdit;
                column.PropertiesEdit.DisplayFormatString = "dd/MM/yyyy";
            });

            settings.Columns.Add(column =>
            {
                column.FieldName = "Total";

                column.ColumnType = MVCxGridViewColumnType.SpinEdit;
                column.Width = 60;
                var spinEditProperties = column.PropertiesEdit as SpinEditProperties;
                spinEditProperties.DisplayFormatString = "c";
                spinEditProperties.DisplayFormatInEditMode = true;
                spinEditProperties.MinValue = 0;
                spinEditProperties.MaxValue = 1000000;
                column.EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.False;
            });

            settings.Columns.Add(column =>
            {
                column.FieldName = "ImporteDescuento";
                column.Caption = "Descuento";

                column.ColumnType = MVCxGridViewColumnType.SpinEdit;
                column.Width = 60;
                var spinEditProperties = column.PropertiesEdit as SpinEditProperties;
                spinEditProperties.DisplayFormatString = "c";
                spinEditProperties.DisplayFormatInEditMode = true;
                spinEditProperties.MinValue = 0;
                spinEditProperties.MaxValue = 1000000;
                column.EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.False;
            });

            settings.Columns.Add(
                column =>
                {
                    column.FieldName = "Estado";
                    column.Caption = "Estado";

                    column.ColumnType = MVCxGridViewColumnType.ComboBox;
                    var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
                    comboBoxProperties.DataSource = ViewBag.Estado;
                    comboBoxProperties.ValueType = typeof(string);
                    comboBoxProperties.DropDownStyle = DropDownStyle.DropDown;
                });           
            
            
            settings.PreRender = (s, e) =>
            {
                var sender = (MVCxGridView)s;
                sender.FocusedRowIndex = 1;                
               
            };
            settings.CommandButtonInitialize = (s, e) =>
            {
                if (e.ButtonType == ColumnCommandButtonType.Edit)
                {
                    MVCxGridView g = s as MVCxGridView;
                    bool value = (bool)g.GetRowValues(e.VisibleIndex, "PermiteEditar");
                    e.Visible = value;
                }
                if (e.ButtonType == ColumnCommandButtonType.Delete)
                {
                    MVCxGridView g = s as MVCxGridView;
                    bool value = (bool)g.GetRowValues(e.VisibleIndex, "PermiteEliminar");
                    e.Visible = value;
                }
            };
            
            settings.SettingsBehavior.AllowFocusedRow = true;
            
            settings.SettingsDetail.AllowOnlyOneMasterRowExpanded = true;
            settings.SettingsDetail.ShowDetailRow = true;


            settings.SetEditFormTemplateContent(c => {

                ViewContext.Writer.Write("<div class=\"edit_form\">");                                    
                
                Html.DevExpress().PageControl(settingsTabEdit =>
                {
                    settingsTabEdit.Name = "pgTabEditMain"; 
                    
                    settingsTabEdit.TabPages.Add(tabpage =>
                    {
                        tabpage.Name = "TabPageCabecera";
                        tabpage.Text = "Cabecera";
                        tabpage.ClientEnabled = false;
                        
                        tabpage.SetContent(() =>
                        {
                            var pedido = ViewData["PedidoEdit"] != null ? ViewData["PedidoEdit"] : c.DataItem;
                            
							ViewContext.Writer.Write("<div class=\"line\">");
							    Html.DevExpress().Label(
								    settingsCliente => 
                                    {
                                        settingsCliente.ControlStyle.CssClass = "label";
                                        settingsCliente.AssociatedControlName = "Cliente.IdCliente";
                                        settingsCliente.Text = "Cliente:";
								    }
							    ).GetHtml();
							    Html.DevExpress().ComboBox(
                                    settingsCliente =>
                                    {
                                        settingsCliente.Name = "Cliente.IdCliente";
                                        settingsCliente.ControlStyle.CssClass = "editor";
                                        settingsCliente.Properties.TextField = "Nombre";
                                        settingsCliente.Properties.ValueField = "IdCliente";
                                        settingsCliente.Properties.ValueType = typeof(int);
                                        settingsCliente.ShowModelErrors = true;
                                        settingsCliente.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
								    }
							    ).BindList(ViewBag.Cliente).Bind(DataBinder.Eval(pedido, "Cliente.IdCliente")).GetHtml();
							ViewContext.Writer.Write("</div>");

                            ViewContext.Writer.Write("<div class=\"line\">");
                                Html.DevExpress().Label(
                                    settingsDate =>
                                    {
                                        settingsDate.ControlStyle.CssClass = "label";
                                        settingsDate.AssociatedControlName = "FechaEntrega";
                                        settingsDate.Text = "Fecha Entrega:";                                    
                                    }
                                ).GetHtml();

                                Html.DevExpress().DateEdit(
                                    settingsDate =>
                                    {
                                        settingsDate.Name = "FechaEntrega";
                                        settingsDate.Properties.DisplayFormatString = "dd/MM/yyyy";
                                        settingsDate.ShowModelErrors = true;
                                        settingsDate.Properties.MinDate = DateTime.Today;
                                        settingsDate.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
                                    }
                                ).Bind(DataBinder.Eval(pedido, "FechaEntrega")).GetHtml(); ;
                            ViewContext.Writer.Write("</div>");

                            ViewContext.Writer.Write("<div class=\"line\">");
                                Html.DevExpress().Label(
                                        edtSettings =>
                                        {
                                            edtSettings.ControlStyle.CssClass = "label";
                                        }
                                    ).GetHtml();
                                   Html.DevExpress().Button(settingsbtn =>
                                   {
                                       settingsbtn.Name = "Continuar";
                                       settingsbtn.ControlStyle.CssClass = "button";
                                       settingsbtn.Text = "Continuar";
                                       settingsbtn.UseSubmitBehavior = false;
                                       settingsbtn.ClientSideEvents.Click = "function(s, e) { pgTabEditMain.SetActiveTabIndex('1'); }";
                                   }).GetHtml();
                                   Html.DevExpress().Button(
                                   btnSettings =>
                                   {
                                       btnSettings.Name = "btnCancel";
                                       btnSettings.ControlStyle.CssClass = "button";
                                       btnSettings.Text = "Cancelar";
                                       btnSettings.ClientSideEvents.Click = "function(s, e){ document.location='" + DevExpressHelper.GetUrl(new { Controller = "Pedidos", Action = "EditPedidosCancelPartial", IdPedido = DataBinder.Eval(pedido, "IdPedido") }) + "'; }";
                                   }).GetHtml();
                                    
                            ViewContext.Writer.Write("</div>");
                        });
                    });

                    settingsTabEdit.TabPages.Add(tabpage =>
                    {
                        tabpage.Name = "TabPageProductos";
                        tabpage.Text = "Productos";
                        tabpage.ClientEnabled = false;

                        tabpage.SetContent(() =>
                        {
                            var idpedido = DataBinder.Eval(c.DataItem, "IdPedido");
                            if (idpedido == null)
                                idpedido = 0;
                            Html.RenderAction("EditPedidoDetallePartial", new { IdPedido = idpedido });

                            ViewContext.Writer.Write("<div class=\"line\">");
                            Html.DevExpress().Label(
                                    edtSettings =>
                                    {
                                        edtSettings.ControlStyle.CssClass = "label";
                                    }
                                )
                                .Render();
                            Html.DevExpress().Button(
                                btnSettings =>
                                {
                                    btnSettings.Name = "btnVolver";
                                    btnSettings.ControlStyle.CssClass = "button";
                                    btnSettings.Text = "Volver";
                                    btnSettings.UseSubmitBehavior = false;
                                    btnSettings.ClientSideEvents.Click = "function(s, e) { pgTabEditMain.SetActiveTabIndex('0'); }";
                                }
                            )
                            .Render();

                            Html.DevExpress().Button(
                                btnSettings =>
                                {
                                    btnSettings.Name = "btnUpdate";
                                    btnSettings.ControlStyle.CssClass = "button";
                                    btnSettings.Text = "Finalizar";
                                    btnSettings.ClientSideEvents.Click = "function(s, e){ gvEditing.UpdateEdit(); }";
                                }
                            )
                            .Render();
                            Html.DevExpress().Button(
                                btnSettings =>
                                {
                                    btnSettings.Name = "btnCancelPrimero";
                                    btnSettings.ControlStyle.CssClass = "button";
                                    btnSettings.Text = "Cancelar";
                                    btnSettings.ClientSideEvents.Click = "function(s, e){ document.location='" + DevExpressHelper.GetUrl(new { Controller = "Pedidos", Action = "EditPedidosCancelPartial", IdPedido = idpedido }) + "'; }";
                                }
                            )
                            .Render();
                            ViewContext.Writer.Write("</div>");
                        });
                    });
                }).GetHtml();
                              
                
                //Cierre el contenido
                ViewContext.Writer.Write("</div>");				 
            });            

            settings.SetDetailRowTemplateContent(c =>
            {
				
				ViewContext.Writer.Write(
                        "Nro Pedido: <b>" + DataBinder.Eval(c.DataItem, "NumeroPedido") + "</b>," +
						"Telefono Cliente: <b>" +
							DataBinder.Eval(c.DataItem, "Cliente.Telefono") + "</b>, Tipo Cliente: <b>" +
							DataBinder.Eval(c.DataItem, "Cliente.TipoCliente.Nombre") + "</b> <b> " +
                            Html.ActionLink("Imprimir Pedido", "ImprimirPedido", new { IdPedido = DataBinder.Eval(c.DataItem, "IdPedido") }) + "</b> <br /><br />"
                          );
                
                Html.RenderAction("EditPedidoDetallePartialVista", new { IdPedido = DataBinder.Eval(c.DataItem, "IdPedido") });
                  
            });



            settings.BeforeGetCallbackResult = (sender, e) =>
            {
                MVCxGridView grid2 = (MVCxGridView)sender;
                if (ViewData["Pedido"] != null)
                {
                    grid2.MakeRowVisible(ViewData["Pedido"]);
                    grid2.DetailRows.ExpandRowByKey(ViewData["Pedido"]);
                }
            };         
        });

	if (ViewData["EditError"] != null)
	{
		grid.SetEditErrorText((string)ViewData["EditError"]);
	}
}
@grid.Bind(Model).GetHtml()